﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;

namespace QuanLyBanHang.Lib
{
    public class KetNoi
    {
        public static string _strcon = @"Data Source=NDTAM-PC\MSSQLSERVER2012;Initial Catalog=QuanLyCuaHangBanDoChoi;User ID=sa;Password=tam123";
        private static SqlConnection _conn;

        public KetNoi()
        {
        }

        public static void OpenConnection()
        {
            if (_conn == null)
            {
                _conn = new SqlConnection(_strcon);
                _conn.Open();
            }
            if (_conn.State == ConnectionState.Closed)
            {
                _conn.Open();
            }
        }

        public static void CloseConnection()
        {
            if ((_conn != null) && (_conn.State == ConnectionState.Open))
            {
                _conn.Close();
            }
        }

        public static DataTable GetTable(string str)
        {
            DataTable dtb = new DataTable();
            try
            {
                OpenConnection();
                SqlDataAdapter da = new SqlDataAdapter(str, _conn);
                SqlCommand cmd = new SqlCommand(str, _conn);
                cmd.ExecuteNonQuery();
                da.Fill(dtb);
                CloseConnection();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return dtb;
        }

        public static int ExcuteSQL(string str)
        {
            int i = 0;
            
            try
            {
                OpenConnection();
                SqlCommand cmd = new SqlCommand(str, _conn);
                i = cmd.ExecuteNonQuery();
                CloseConnection();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return i;
        }
    }
}
